/**
 * 
 */
package com.tech.freak.pyp;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.content.Loader.OnLoadCompleteListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.tech.freak.pyp.data.PicoyPlaca.PYP;
import com.tech.freak.pyp.model.CityRestriction;

/**
 * @author julian
 *
 */
public class ShowPypData extends ListActivity{

	private static final String TAG = "ShowPypData";
	
	private static final int DIALOG_ADD_CITY = 0;
	private static final int DIALOG_DELETE_CITY = 1;
	
	
	private CursorLoader loader;
	
	private OnLoadCompleteListener<Cursor> loaderListener;
	
	private Button city_actions_add;
	private Button city_actions_delete;
	
	private ArrayList<CharSequence>	marked_cities = new ArrayList<CharSequence>();
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_data);
		
		city_actions_add = (Button) findViewById(R.id.city_actions_add);
		city_actions_add.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				showDialog(DIALOG_ADD_CITY);
				
			}
		});
		city_actions_delete = (Button) findViewById(R.id.city_actions_delete);
		city_actions_delete.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				showDialog(DIALOG_DELETE_CITY);
				
			}
		});
		prepareDataLoader();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onResume();
		
		loadData();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		super.onPause();
		
		if(loader.isStarted()){
			loader.unregisterListener(loaderListener);
			loader.stopLoading();
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_ADD_CITY:
			return createAddCityDialog();
		case DIALOG_DELETE_CITY:
			final CharSequence[] citylist = getCityList();
			return new AlertDialog.Builder(ShowPypData.this)
				.setTitle(R.string.city_actions_delete_label)
				//.setMessage(R.string.city_actions_delete_select_label)
				.setMultiChoiceItems(citylist, null, new OnMultiChoiceClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which, boolean isChecked) {
						Log.d(TAG, "Clicked which="+which+" ischecked="+isChecked);
						if(isChecked){
							Log.d(TAG, "City = "+ citylist[which]);
							marked_cities.add(citylist[which]);
						}else{
							marked_cities.remove(citylist[which]);
						}
							
					}
				})
				.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Utils.deleteCities(getContentResolver(), marked_cities);
						//Update widgets
						sendBroadcast(new Intent().setAction(Utils.UPDATE_WIDGET));
						
					}
					
				})
				.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						
					}
				})
				.create();
		default:
			return null;
		}
		
	}
	

	/* (non-Javadoc)
	 * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
	 */
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
		
		switch (id) {
		case DIALOG_DELETE_CITY:
			removeDialog(DIALOG_DELETE_CITY);
			break;
		default:
			break;
		}
	}

	/* (non-Javadoc)
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView, android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		startEditCityActivity(id);
		
	}

	private void prepareDataLoader() {
		String[] projection = new String[] {PYP._ID , 
				PYP.CITY,
				PYP.MONDAY,
				PYP.TUESDAY,
				PYP.WEDNSEDAY,
				PYP.THURSDAY,
				PYP.FRIDAY,
				PYP.SATURDAY,
				PYP.SUNDAY
				};
		loader = new CursorLoader(this, PYP.CONTENT_URI, projection, null,null, null);
		
	}
	
	private void loadData(){
		
		loaderListener = new OnLoadCompleteListener<Cursor>() {

			@Override
			public void onLoadComplete(Loader<Cursor> loader, Cursor data) {
				bindData(data);
			}
		};
		
		loader.registerListener(0, loaderListener);
		loader.startLoading();
	}

	protected void bindData(Cursor cursor) {
		PyPDataAdapter adapter = new PyPDataAdapter(this, cursor);
		setListAdapter(adapter);
		setListAnimation();
	}
	
	/**
	 * Sets the list animation.
	 */
	protected void setListAnimation() {
		AnimationSet set = new AnimationSet(true);
		Animation animation = new AlphaAnimation(0.0f, 1.0f);
		animation.setDuration(50);
		set.addAnimation(animation);
		animation = new TranslateAnimation(
		                Animation.RELATIVE_TO_SELF, -1.0f,Animation.RELATIVE_TO_SELF, 0.0f,
		                Animation.RELATIVE_TO_SELF, 0.0f,Animation.RELATIVE_TO_SELF, 0.0f
		            );
		animation.setDuration(200);
		set.addAnimation(animation);
		LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);
		
		ListView lv = getListView();
		lv.setLayoutAnimation(controller);
	}
	
	private CharSequence[] getCityList() {
		CharSequence[] city_list = null;
		CityRestriction[] mCityRestrictions = Utils.getCityRestrictions(getContentResolver());
		if(mCityRestrictions!=null){
	        city_list = new CharSequence[mCityRestrictions.length];
	        
	        for (int i = 0; i < mCityRestrictions.length; i++) {
				city_list[i] = mCityRestrictions[i].getCity();
			}
		}
		
		return city_list;
	}
	
	private Dialog createAddCityDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(ShowPypData.this);
		LayoutInflater inflater = getLayoutInflater();
		View dialog_add_city = inflater.inflate(R.layout.dialog_add_city, null);
		EditText city = (EditText) dialog_add_city.findViewById(R.id.city_name);
		dialog_add_city.setTag(city);
		builder.setView(dialog_add_city);
		builder.setTitle(R.string.city_actions_add_label);
		builder.setPositiveButton(android.R.string.ok,new SaveCityListener(city));
		builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				
			}
			
		});
		
		return builder.create();
	}

	private class SaveCityListener implements DialogInterface.OnClickListener{

		private final EditText city;
		public SaveCityListener(EditText city) {
			this.city= city;
		}
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			String cityName = city.getText().toString();
			if(!TextUtils.isEmpty(cityName)){
				try{
					Uri uri = Utils.createCity(getContentResolver(), cityName);
					long id = Long.parseLong(uri.getPathSegments().get(1));
					startEditCityActivity(id);
				}catch (Exception e) {
					Toast.makeText(getApplicationContext(),R.string.notification_update_city_error ,Toast.LENGTH_SHORT).show();
				}
			}
			else
				Toast.makeText(getApplicationContext(),R.string.notification_update_city_error ,Toast.LENGTH_SHORT).show();
			
			dialog.dismiss();
		}
		
		
	}
	
	private void startEditCityActivity(long id) {
		Intent intent = new Intent(this, EditCity.class);
		intent.putExtra(EditCity.DATA_ID, id);
		startActivity(intent);
		
	}
}
